package server;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

import static sun.management.jmxremote.ConnectorBootstrap.PropertyNames.PORT;

/**
 * 超市管理系统服务器主类
 */
public class Server {

    private static List<ClientHandler> clientHandlers;

    public static void main(String[] args) {
        System.out.println("超市管理系统服务器启动，端口: " + PORT);
        
        try (ServerSocket serverSocket = new ServerSocket()) {
            while (true) {
                // 等待客户端连接
                Socket clientSocket = serverSocket.accept();
                System.out.println("新客户端连接: " + clientSocket.getInetAddress());
                
                // 创建客户端处理器
                ClientHandler clientHandler = new ClientHandler(clientSocket, clientHandlers);
                clientHandlers.add(clientHandler);
                
                // 启动线程处理客户端
                Thread thread = new Thread(clientHandler);
                thread.start();
            }
        } catch (IOException e) {
            System.err.println("服务器错误: " + e.getMessage());
        }
    }
    
    /**
     * 向指定用户发送消息
     */
    public static void sendToClient(String message, String userId) {
        for (ClientHandler handler : clientHandlers) {
            if (handler.getUserId().equals(userId)) {
                handler.sendMessage(message);
                break;
            }
        }
    }
    
    /**
     * 向指定角色的所有用户广播消息
     */
    public static void broadcastToRole(String message, String role) {
        for (ClientHandler handler : clientHandlers) {
            if (handler.getRole().equals(role)) {
                handler.sendMessage(message);
            }
        }
    }
}
    